#include "xmppcore/message.h"
#include "xmppcore/xmlwriter.h"
#include "xmppcore/constants.h"

namespace yoohoo_xmppcore {

const ProtocolKey Message::PROTOCOL_KEY = ProtocolKey(XMPP_STRING_MESSAGE);

Message::Message() {
	_d->type = "normal";
	_md = new MessageSharedData;
}

Message::Message(const Message& other) : Stanza(other), _md(other._md) {
}

void Message::setSubjects(QList<XmlLangText> subjects) {
	_md->subjects = subjects;
}

QList<XmlLangText>& Message::subjects() {
	return _md->subjects;
}

void Message::setBodies(QList<XmlLangText> bodies) {
	_md->bodies = bodies;
}

QList<XmlLangText>& Message::bodies() {
	return _md->bodies;
}

void Message::setThread(QString thread) {
	_md->thread = thread;
}

QString Message::thread() const {
	return _md->thread;
}

Stanza::StanzaKind Message::stanzaKind() const {
	return Stanza::StanzaKindMessage;
}

Message::MessageType Message::messageType() const {
	return _md->messageType;
}

void Message::setMessageType(Message::MessageType messageType) {
	_md->messageType = messageType;
	if (Message::MessageTypeChat == _md->messageType) {
		_d->type = "chat";
	} else if (Message::MessageTypeGroupChat == _md->messageType) {
		_d->type = "groupchat";
	} else if (Message::MessageTypeHeadline == _md->messageType) {
		_d->type = "headline";
	} else {
		_d->type = "normal";
	}
}

void Message::doToXml(XmlWriter* xmlWriter) {
	if (!_md->subjects.isEmpty()) {
		foreach (XmlLangText subject, _md->subjects) {
			xmlWriter->writeStartElement("subject");
			if (!subject.xmlLang().isEmpty()) {
				xmlWriter->writeAttribute("xml:lang", subject.xmlLang());
			}

			if (!subject.text().isEmpty()) {
				xmlWriter->writeCharacters(subject.text());
			}

			xmlWriter->writeEndElement();
		}
	}

	if (!_md->bodies.isEmpty()) {
		foreach (XmlLangText body, _md->bodies) {
			xmlWriter->writeStartElement("body");
			if (!body.xmlLang().isEmpty()) {
				xmlWriter->writeAttribute("xml:lang", body.xmlLang());
			}

			if (!body.text().isEmpty()) {
				xmlWriter->writeCharacters(body.text());
			}

			xmlWriter->writeEndElement();
		}
	}

	if (!_md->thread.isEmpty()) {
		xmlWriter->writeStartElement("thread");
		xmlWriter->writeCharacters(_md->thread);
		xmlWriter->writeEndElement();
	}
}

MessageSharedData::MessageSharedData() : messageType(Message::MessageTypeNormal) {
}

MessageSharedData::MessageSharedData(const MessageSharedData& other) : QSharedData(other), subjects(other.subjects),
	bodies(other.bodies), thread(other.thread), messageType(other.messageType) {
}

}
